package com.itheima;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.searchClients;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.itheima.pojo.ItemDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class testItem {

    @Autowired
    private searchClients searchClients;

    private RestHighLevelClient client;


    @Test
    public void testAdd() throws IOException {
        BulkRequest request = new BulkRequest("item");

        PageDTO<Item> itemPageDTO = searchClients.itemList(1, 5);

        Long total = itemPageDTO.getTotal();

        for (Integer i = 0; i*200 < total; i++) {

            PageDTO<Item> itemPageDTO1 = searchClients.itemList(i, 400);

            List<Item> list = itemPageDTO1.getList();

            for (Item item : list) {

                ItemDoc itemDoc = new ItemDoc(item);

                request.add(new IndexRequest().id(String.valueOf(itemDoc.getId())).source(JSON.toJSONString(itemDoc),XContentType.JSON));
            }
            BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
            System.out.println(responses.status());

        }

    }

    @BeforeEach
    public void init(){
        this.client= new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://wl.coolyou.top:9200")
        ));
    }


    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

}
